I want to get the file name from a URL. But the problem is it's not ending with an extension.
For ex开发者_Python百科ample, http://something.com/1245/65/. On clicking this URL, we will get a PDF file. How do I store the file name of that file in a variable?
<?php
header('Content-Type: text/plain');
$curl = curl_init('http://localhost/fakefile.php');
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'HEAD');
if (($response = curl_exec($curl)) !== false)
{
if (curl_getinfo($curl, CURLINFO_HTTP_CODE) == '200')
{
var_dump($response);
$reDispo = '/^Content-Disposition: .*?filename=(?<f>[^\s]+|\x22[^\x22]+\x22)\x3B?.*$/m';
if (preg_match($reDispo, $response, $mDispo))
{
$filename = trim($mDispo['f'],' ";');
echo "Filename Found: $filename";
}
}
}
curl_close($curl);
That would parse the Content-Disposition
line for the filename=foo.bar information (assuming it does render the file directly out using this method.)
If you issue a GET
request for http://something.com/1245/65/
and it returns you a PDF file -- that is, something with Content-Type = application/pdf
-- you have absolutely no way of knowing the actual name of the .pdf
file that was sent to you.
In the web application that I work on, I generate and combine PDF files and stream them directly to the browser in response to just such a GET
request - no actual file even exists so there definitely is not filename.
If you are in control of the server you could invent a way to communicate the name to the requester, or if it's your PHP code that wants to know (which runs on the server) you could provide some other server-side hook to find the filename.
Curiously enough, trying the same code you have above was making my webserver hang too. I replaced this code:
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'HEAD');
With this:
curl_setopt($ch, CURLOPT_NOBODY, true);
Say if you have a url
$url = 'www/htdocs/lib/inc.php'
$pathifo = pathinfo($url)// Return Array
when you say $pathinfo['PATHINFO_FILENAME'] //It would output inc
精彩评论