How do I use PHP to grab the name of the file? - php

what I want to do is PHP to look at the url and just grab the name of the file, without me needing to enter a path or anything (which would be dynamic anyway). E.G.
http://google.com/info/hello.php, I want to get the 'hello' bit.
Help?
Thanks.

You need basename and explode to get name without extension:
$name = basename($_SERVER['REQUEST_URI']);
$name_array = explode('.', $name);
echo $name_array[0];

$filename = __FILE__;
Now you can split this on the dot, for example
$filenameChunks = split(".", $filename);
$nameOfFileWithoutDotPHP = $filenameChunks[0];

This is safe way to easily grab the filename without extension
$info = pathinfo(__FILE__);
$filename = $info['filename'];

$_SERVER['REQUEST_URI'] contains the requested URI path and query. You can then use parse_url to get the path and basename to get just the file name:
basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '.php')

http://php.net/manual/en/function.basename.php
$file = basename(__FILE__); // hello.php
$file = explode('.',$file); // array
unset($file[count($file)-1]); // unset array key that has file extension
$file = implode('.',$file); // implode the pieces back together
echo $file; // hello

You could to this with parse_url combined with pathinfo
Here's an example
$parseResult = parse_url('http://google.com/info/hello.php');
$result = pathinfo($parseResult['path'], PATHINFO_FILENAME);
$result will contain "hello"
More info on the functions can be found here:
parse_url
pathinfo

Related

PHP trouble getting symlinked "file name" without full path [duplicate]

For example, how do I get Output.map
from
F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map
with PHP?
You're looking for basename.
The example from the PHP manual:
<?php
$path = "/home/httpd/html/index.php";
$file = basename($path); // $file is set to "index.php"
$file = basename($path, ".php"); // $file is set to "index"
?>
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:
<?php
$xmlFile = pathinfo('/usr/admin/config/test.xml');
function filePathParts($arg1) {
echo $arg1['dirname'], "\n";
echo $arg1['basename'], "\n";
echo $arg1['extension'], "\n";
echo $arg1['filename'], "\n";
}
filePathParts($xmlFile);
?>
This will return:
/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'];
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.
Ref: http://php.net/manual/en/splfileinfo.getfilename.php
$info = new SplFileInfo('/path/to/foo.txt');
var_dump($info->getFilename());
o/p: string(7) "foo.txt"
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:
<?php
$path = "/home/httpd/html/index.php";
$file = basename($path); // $file is set to "index.php"
$file = basename($path, ".php"); // $file is set to "index"
?>
Or, in your case:
$full = 'F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map';
var_dump(basename($full));
You'll get:
string(10) "Output.map"
Try this:
echo basename($_SERVER["SCRIPT_FILENAME"], '.php')
basename() has a bug when processing Asian characters like Chinese.
I use this:
function get_basename($filename)
{
return preg_replace('/^.+[\\\\\\/]/', '', $filename);
}
$filename = basename($path);
You can use the basename() function.
To do this in the fewest lines I would suggest using the built-in DIRECTORY_SEPARATOR constant along with explode(delimiter, string) to separate the path into parts and then simply pluck off the last element in the provided array.
Example:
$path = 'F:\Program Files\SSH Communications Security\SSH SecureShell\Output.map'
//Get filename from path
$pathArr = explode(DIRECTORY_SEPARATOR, $path);
$filename = end($pathArr);
echo $filename;
>> 'Output.map'
To get the exact file name from the URI, I would use this method:
<?php
$file1 =basename("http://localhost/eFEIS/agency_application_form.php?formid=1&task=edit") ;
//basename($_SERVER['REQUEST_URI']); // Or use this to get the URI dynamically.
echo $basename = substr($file1, 0, strpos($file1, '?'));
?>
It's simple. For example:
<?php
function filePath($filePath)
{
$fileParts = pathinfo($filePath);
if (!isset($fileParts['filename']))
{
$fileParts['filename'] = substr($fileParts['basename'], 0, strrpos($fileParts['basename'], '.'));
}
return $fileParts;
}
$filePath = filePath('/www/htdocs/index.html');
print_r($filePath);
?>
The output will be:
Array
(
[dirname] => /www/htdocs
[basename] => index.html
[extension] => html
[filename] => index
)
$image_path = "F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map";
$arr = explode('\\',$image_path);
$name = end($arr);
<?php
$windows = "F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map";
/* str_replace(find, replace, string, count) */
$unix = str_replace("\\", "/", $windows);
print_r(pathinfo($unix, PATHINFO_BASENAME));
?>
body, html, iframe {
width: 100% ;
height: 100% ;
overflow: hidden ;
}
<iframe src="https://ideone.com/Rfxd0P"></iframe>

Get only the filename with certain extension in a folder - PHP [duplicate]

For example, how do I get Output.map
from
F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map
with PHP?
You're looking for basename.
The example from the PHP manual:
<?php
$path = "/home/httpd/html/index.php";
$file = basename($path); // $file is set to "index.php"
$file = basename($path, ".php"); // $file is set to "index"
?>
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:
<?php
$xmlFile = pathinfo('/usr/admin/config/test.xml');
function filePathParts($arg1) {
echo $arg1['dirname'], "\n";
echo $arg1['basename'], "\n";
echo $arg1['extension'], "\n";
echo $arg1['filename'], "\n";
}
filePathParts($xmlFile);
?>
This will return:
/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'];
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.
Ref: http://php.net/manual/en/splfileinfo.getfilename.php
$info = new SplFileInfo('/path/to/foo.txt');
var_dump($info->getFilename());
o/p: string(7) "foo.txt"
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:
<?php
$path = "/home/httpd/html/index.php";
$file = basename($path); // $file is set to "index.php"
$file = basename($path, ".php"); // $file is set to "index"
?>
Or, in your case:
$full = 'F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map';
var_dump(basename($full));
You'll get:
string(10) "Output.map"
Try this:
echo basename($_SERVER["SCRIPT_FILENAME"], '.php')
basename() has a bug when processing Asian characters like Chinese.
I use this:
function get_basename($filename)
{
return preg_replace('/^.+[\\\\\\/]/', '', $filename);
}
$filename = basename($path);
You can use the basename() function.
To do this in the fewest lines I would suggest using the built-in DIRECTORY_SEPARATOR constant along with explode(delimiter, string) to separate the path into parts and then simply pluck off the last element in the provided array.
Example:
$path = 'F:\Program Files\SSH Communications Security\SSH SecureShell\Output.map'
//Get filename from path
$pathArr = explode(DIRECTORY_SEPARATOR, $path);
$filename = end($pathArr);
echo $filename;
>> 'Output.map'
To get the exact file name from the URI, I would use this method:
<?php
$file1 =basename("http://localhost/eFEIS/agency_application_form.php?formid=1&task=edit") ;
//basename($_SERVER['REQUEST_URI']); // Or use this to get the URI dynamically.
echo $basename = substr($file1, 0, strpos($file1, '?'));
?>
It's simple. For example:
<?php
function filePath($filePath)
{
$fileParts = pathinfo($filePath);
if (!isset($fileParts['filename']))
{
$fileParts['filename'] = substr($fileParts['basename'], 0, strrpos($fileParts['basename'], '.'));
}
return $fileParts;
}
$filePath = filePath('/www/htdocs/index.html');
print_r($filePath);
?>
The output will be:
Array
(
[dirname] => /www/htdocs
[basename] => index.html
[extension] => html
[filename] => index
)
$image_path = "F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map";
$arr = explode('\\',$image_path);
$name = end($arr);
<?php
$windows = "F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map";
/* str_replace(find, replace, string, count) */
$unix = str_replace("\\", "/", $windows);
print_r(pathinfo($unix, PATHINFO_BASENAME));
?>
body, html, iframe {
width: 100% ;
height: 100% ;
overflow: hidden ;
}
<iframe src="https://ideone.com/Rfxd0P"></iframe>

How to get file name from url without $_GET variable?

http://localhost/mc/site-01-up/index.php?c=lorem-ipsum
$address = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$stack = explode('/', $_SERVER["REQUEST_URI"]);
$file = array_pop($stack);
echo $file;
result - index.php?c=lorem-ipsum
How to get just file name (index.php) without $_GET variable, using array_pop if possible?
Another method that can get the filename is by using parse_url — Parses a URL and return its components
<?php
$url = "http://localhost/mc/site-01-up/index.php?c=lorem-ipsum";
$data = parse_url($url);
$array = explode("/",$data['path']);
$filename = $array[count($array)-1];
var_dump($filename);
Result
index.php
EDIT:
Sorry for posting this answer as it is almost identical to the selected one. I didnt see the answer so posted. But I cannot delete this as it is seen as a bad practice by moderators.
I will follow parse_url() like below (easy to understand):-
<?php
$url = 'http://localhost/mc/site-01-up/index.php?c=lorem-ipsum';
$url= parse_url($url);
print_r($url); // to check what parse_url() will outputs
$url_path = explode('/',$url['path']); // explode the path part
$file_name = $url_path[count($url_path)-1]; // get last index value which is your desired result
echo $file_name;
?>
Output:- https://eval.in/606839
Note:- tested with your given URL. Check for other type of URL's at your end. thanks.
Try this, not tested:
$file = $_SERVER["SCRIPT_NAME"];
$parts = Explode('/', $file);
$file = $parts[count($parts) - 1];
echo $file;
One way of doing it would be to simply get the basename() of the file and then strip-out all the Query Part using regex or better still simply do pass the $_SERVER['PHP_SELF'] result to the basename() Function. Both will yield the same result though the 2nd approach seems a little more intuitive.
<?php
$fileName = preg_replace("#\?.*$#", "", basename("http://localhost/mc/site-01-up/index.php?c=lorem-ipsum"));
echo $fileName; // DISPLAYS: index.php
// OR SHORTER AND SIMPLER:
$fileName = basename($_SERVER['PHP_SELF']);
echo $fileName; // DISPLAYS: index.php
If you are trying to use the GET method without variable name, another option would be using the $_SERVER["QUERY_STRING"]
http://something.com/index.php?=somestring
$_SERVER["QUERY_STRING"] would return "somestring"

Getting a File Name Using PHP [duplicate]

For example, how do I get Output.map
from
F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map
with PHP?
You're looking for basename.
The example from the PHP manual:
<?php
$path = "/home/httpd/html/index.php";
$file = basename($path); // $file is set to "index.php"
$file = basename($path, ".php"); // $file is set to "index"
?>
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:
<?php
$xmlFile = pathinfo('/usr/admin/config/test.xml');
function filePathParts($arg1) {
echo $arg1['dirname'], "\n";
echo $arg1['basename'], "\n";
echo $arg1['extension'], "\n";
echo $arg1['filename'], "\n";
}
filePathParts($xmlFile);
?>
This will return:
/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'];
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.
Ref: http://php.net/manual/en/splfileinfo.getfilename.php
$info = new SplFileInfo('/path/to/foo.txt');
var_dump($info->getFilename());
o/p: string(7) "foo.txt"
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:
<?php
$path = "/home/httpd/html/index.php";
$file = basename($path); // $file is set to "index.php"
$file = basename($path, ".php"); // $file is set to "index"
?>
Or, in your case:
$full = 'F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map';
var_dump(basename($full));
You'll get:
string(10) "Output.map"
Try this:
echo basename($_SERVER["SCRIPT_FILENAME"], '.php')
basename() has a bug when processing Asian characters like Chinese.
I use this:
function get_basename($filename)
{
return preg_replace('/^.+[\\\\\\/]/', '', $filename);
}
$filename = basename($path);
You can use the basename() function.
To do this in the fewest lines I would suggest using the built-in DIRECTORY_SEPARATOR constant along with explode(delimiter, string) to separate the path into parts and then simply pluck off the last element in the provided array.
Example:
$path = 'F:\Program Files\SSH Communications Security\SSH SecureShell\Output.map'
//Get filename from path
$pathArr = explode(DIRECTORY_SEPARATOR, $path);
$filename = end($pathArr);
echo $filename;
>> 'Output.map'
To get the exact file name from the URI, I would use this method:
<?php
$file1 =basename("http://localhost/eFEIS/agency_application_form.php?formid=1&task=edit") ;
//basename($_SERVER['REQUEST_URI']); // Or use this to get the URI dynamically.
echo $basename = substr($file1, 0, strpos($file1, '?'));
?>
It's simple. For example:
<?php
function filePath($filePath)
{
$fileParts = pathinfo($filePath);
if (!isset($fileParts['filename']))
{
$fileParts['filename'] = substr($fileParts['basename'], 0, strrpos($fileParts['basename'], '.'));
}
return $fileParts;
}
$filePath = filePath('/www/htdocs/index.html');
print_r($filePath);
?>
The output will be:
Array
(
[dirname] => /www/htdocs
[basename] => index.html
[extension] => html
[filename] => index
)
$image_path = "F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map";
$arr = explode('\\',$image_path);
$name = end($arr);
<?php
$windows = "F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map";
/* str_replace(find, replace, string, count) */
$unix = str_replace("\\", "/", $windows);
print_r(pathinfo($unix, PATHINFO_BASENAME));
?>
body, html, iframe {
width: 100% ;
height: 100% ;
overflow: hidden ;
}
<iframe src="https://ideone.com/Rfxd0P"></iframe>

Get only filename from url in php without any variable values which exist in the url

I want to get filename without any $_GET variable values from a URL in php?
My URL is http://learner.com/learningphp.php?lid=1348
I only want to retrieve the learningphp.php from the URL?
How to do this?
I used basename() function but it gives all the variable values also: learntolearn.php?lid=1348 which are in the URL.
This should work:
echo basename($_SERVER['REQUEST_URI'], '?' . $_SERVER['QUERY_STRING']);
But beware of any malicious parts in your URL.
Following steps shows total information about how to get file, file with extension, file without extension. This technique is very helpful for me. Hope it will be helpful to you too.
$url = 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png';
$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
Is better to use parse_url to retrieve only the path, and then getting only the filename with the basename. This way we also avoid query parameters.
<?php
// url to inspect
$url = 'http://www.example.com/image.jpg?q=6574&t=987';
// parsed path
$path = parse_url($url, PHP_URL_PATH);
// extracted basename
echo basename($path);
?>
Is somewhat similar to Sultan answer excepting that I'm using component parse_url parameter, to obtain only the path.
Use parse_url() as Pekka said:
<?php
$url = 'http://www.example.com/search.php?arg1=arg2';
$parts = parse_url($url);
$str = $parts['scheme'].'://'.$parts['host'].$parts['path'];
echo $str;
?>
http://codepad.org/NBBf4yTB
In this example the optional username and password aren't output!
Your URL:
$url = 'http://learner.com/learningphp.php?lid=1348';
$file_name = basename(parse_url($url, PHP_URL_PATH));
echo $file_name;
output: learningphp.php
You can use,
$directoryURI =basename($_SERVER['SCRIPT_NAME']);
echo $directoryURI;
An other way to get only the filename without querystring is by using parse_url and basename functions :
$parts = parse_url("http://example.com/foo/bar/baz/file.php?a=b&c=d");
$filename = basename($parts["path"]); // this will return 'file.php'
Try the following code:
For PHP 5.4.0 and above:
$filename = basename(parse_url('http://learner.com/learningphp.php?lid=1348')['path']);
For PHP Version < 5.4.0
$parsed = parse_url('http://learner.com/learningphp.php?lid=1348');
$filename = basename($parsed['path']);
$filename = pathinfo( parse_url( $url, PHP_URL_PATH ), PATHINFO_FILENAME );
Use parse_url to extract the path from the URL, then pathinfo returns the filename from the path
The answer there assumes you know that the URL is coming from a request, which it may very well not be. The generalized answer would be something like:
$basenameWithoutParameters = explode('?', pathinfo($yourURL, PATHINFO_BASENAME))[0];
Here it just takes the base path, and splits out and ignores anything ? and after.
$url = "learner.com/learningphp.php?lid=1348";
$l = parse_url($url);
print_r(stristr($l['path'], "/"));
Use this function:
function getScriptName()
{
$filename = baseName($_SERVER['REQUEST_URI']);
$ipos = strpos($filename, "?");
if ( !($ipos === false) ) $filename = substr($filename, 0, $ipos);
return $filename;
}
May be i am late
$e = explode("?",basename($_SERVER['REQUEST_URI']));
$filename = $e[0];

Categories