- How to get file name from a path in PHP ?
- Get the Current Script File Name in PHP
- Sample Code to Get the Current Script File Name in PHP
- How to get file name from a path in PHP ?
- Get file name of a URL in PHP
- 4 Answers 4
- How do I get a file name from a full path with PHP?
- 14 Answers 14
- extract downloaded url filename [closed]
- 1 Answer 1
How to get file name from a path in PHP ?
: Current file name without PHP file extension. : Current file name without PHP file extension.
Get the Current Script File Name in PHP
Your script may need the current file name with the directory name in which it is currently executing. In this tutorial article, we will discuss how to get the filename of the current script inside the project.
PHP provides various ways to find out the Current file name. First, we will briefly understand all the parameters & methods and then combine them to get the result.
- __FILE__ : PHP provides 9 magical constants which are used on the basis of their use. These constants are created by various extensions. All of these constants are resolved during compile time. __FILE__ is one of such a magic constant that gives you the filesystem path to the current .PHP file.
- $_SERVER : $_SERVER is an array that contains information about headers, paths, and script locations. The webserver creates all this information.
- PHP_SELF : PHP_SELF is a variable used to get the filename of the currently executing script. It is relative to the document root. When the user runs this command in the command line, it will print the information about the script name.
- SCRIPT_FILENAME : This is a variable used to get the filename of the currently executing script, and the only difference is its path is absolute.
- SCRIPT_NAME : It Contains the current script’s path. This is useful for pages that need to point to themselves.
- REQUEST_URI : The URI was given to access the page’s location, for instance, /index.html .
Now let’s use all the above commands together to get the file name.
Parent file relative URL with the file extension. For example, `http://example.com/parentFolder/child.php` would be `/parentFolder/child.php`.
- $_SERVER[‘SCRIPT_FILENAME’] : parent file full URL with a file extension
- $_SERVER[‘REQUEST_URI’] : parent file parent folder name with
The inbuilt PHP function basename() returns the base name of a file if the path of the file is provided as a parameter to the basename() function.
- basename(__FILE__) : Current file name with php file extension.
- basename(__FILE__, ‘.php’) : Current file name without PHP file extension.
- basename($_SERVER[‘PHP_SELF’], «.php») : Current file name without PHp file extension.
- basename($_SERVER[‘PHP_SELF’]) : Current file name with php file extension.
- pathinfo(__FILE__, PATHINFO_FILENAME) : Current file name without PHP file extension.
Sample Code to Get the Current Script File Name in PHP
Get the Current Script File Name in PHP, The inbuilt PHP function basename() returns the base name of a file if the path of the file is provided as a parameter to the basename() function. basename(__FILE__) : Current file name with PHP file extension.
How to get file name from a path in PHP ?
In this article, we will see how to get the file name from the path in PHP, along with understanding its implementation through the examples. We have given the full path & we need to find the file name from the file path. For this, we will following below 2 methods:
Input : path = /testweb/var/www/mywebsite/htdocs/home.php
Output : home.php
Input : path = /testweb/var/www/mywebsite/htdocs/abc.txt
Output : abc.txt
We will understand both functions with the help of examples.
Method 1: Using basename() function:
The basename() function is an inbuilt function that returns the base name of a file if the path of the file is provided as a parameter to the basename() function.
$filename = basename(path, suffix);
The path is a required field that specifies the path which is to be checked. The suffix is an optional field that specifies a file extension. If the filename has this file extension, the file extension will not show.
Example : This example describes the use of the basename() function that returns the base name of the file.
Get file name of a URL in PHP
I want to get the file name from a URL. But the problem is it’s not ending with an extension. For example, 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?
4 Answers 4
[^\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.)
@djdance not if you are using *nix or care about case of filename. Better off specifying i flag in regex pattern.
sure, I just saw so on another server (Windows, possibly). And could you give me an example of i flag in regex 😉
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.
How do I get a file name from a full path with PHP?
For example, how do I get Output.map from F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map with PHP?
14 Answers 14
The example from the PHP manual:
I would suggest pathinfo over basename as Metafaniel posted below. pathinfo() will give you an array with the parts of the path. Or for the case here, you can just specifically ask for the filename. So pathinfo(‘/var/www/html/index.php’, PATHINFO_FILENAME) should return ‘index.php’ PHP Pathinfo documentation
@OnethingSimple Check the docs again. counter intuitive though it is, you’ll want PATHINFO_BASENAME to get the full index.php . PATHINFO_FILENAME will give you index .
in any case, for a unicode compatible method, mb_substr($filepath,mb_strrpos($filepath,’/’,0,’UTF-16LE’),NULL,’UTF-16LE’) — just replace UTF-16LE with whatever characterset your filesystem uses (NTFS and ExFAT uses UTF16)
I’ve done this using the function PATHINFO which creates an array with the parts of the path for you to use! For example, you can do this:
/usr/admin/config test.xml xml test
The use of this function has been available since PHP 5.2.0!
Then you can manipulate all the parts as you need. For example, to use the full path, you can do this:
$fullPath = $xmlFile['dirname'] . '/' . $xmlFile['basename'];
@FrankConijn Because of your question, I can see you’re using a web browser with my code snippet. In that case: yes, you have to replace \n with
. My code is meant to be run using the command line, thus the line breaks with \n work. Greetings.
There are several ways to get the file name and extension. You can use the following one which is easy to use.
$url = 'http://www.nepaltraveldoor.com/images/trekking/nepal/annapurna-region/Annapurna-region-trekking.jpg'; $file = file_get_contents($url); // To get file $name = basename($url); // To get file name $ext = pathinfo($url, PATHINFO_EXTENSION); // To get extension $name2 =pathinfo($url, PATHINFO_FILENAME); // File name without extension
With SplFileInfo:
SplFileInfo The SplFileInfo class offers a high-level object oriented interface to information for an individual file.
$info = new SplFileInfo('/path/to/foo.txt'); var_dump($info->getFilename());
The basename function should give you what you want:
Given a string containing a path to a file, this function will return the base name of the file.
For instance, quoting the manual’s page:
$full = 'F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map'; var_dump(basename($full));
echo basename($_SERVER["SCRIPT_FILENAME"], '.php')
basename() has a bug when processing Asian characters like Chinese.
function get_basename($filename) < return preg_replace('/^.+[\\\\\\/]/', '', $filename); >
I don’t think its a bug, in the docs its mentioned: Caution basename() is locale aware, so for it to see the correct basename with multibyte character paths, the matching locale must be set using the setlocale() function. . But I also prefere to use preg_replace, because the directory separator differ between operating systems. On Ubuntu `\` is not a directoy separator and basename will have no effect on it.
extract downloaded url filename [closed]
It’s difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
i am trying to figure out how to get the actual file name from the downloaded url.here is the download url .please note that this url is direct there is no redirect.
http://xyzjsjwekeke.com/download/314543&r=515
how_to_prepare_for_interview.pdf
but in download url theere is nothing like that . i tried base extraxt but it gives output as last words after slash of url given
$filename = array_shift(explode('?', basename($url))); echo $filename;
What exactly are you trying to achieve here — do you want to know how to set a file name when sending a download to the browser?
@Pekka i want to extract the actual file name so that i can store that name in my database but the file name like 314543&r=515 is of no use i want to store actual file name in above case how_to_prepare_for_interview.pdf
@Payal Malhotra: If you want that, I wonder what made you choosing basename and explode and array_shift ? By best intentions I can not imagine how that ever would make sense. Do you know what those functions are for?
@PayalMalhotra basename is simply a string manipulation function. It won’t access the URL so it can’t give you anything as output that you didn’t put into it.
1 Answer 1
There is no way to get a file name from the url that does not have the file name in the first place.
http://xyzjsjwekeke.com/download/314543&r=515 ^----- Probably ID to the file
It probably takes the ID from the url and get the real from a storage system eg. MySQL, CDN etc) send sends its back via :
header('Content-disposition: attachment; filename='.$realName);
The way to get such a file name is directly from the HTTP headers. get the header information using Headers get_headers and extract the file name
$headers = get_headers("http://xyzjsjwekeke.com/download/314543&r=515p",true); $headers = array_combine(array_map("strtolower",array_keys($headers)),$headers); $fileName = isset($headers['content-disposition']) ? strstr($headers['content-disposition'], "=") : null ; $fileName = trim($fileName,"=\"'"); var_dump($fileName);