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"
Related
I would like to get a website filename after domain without the extension and any query string.
I try to resolve with basename, but if the user put ? after .php the output is display incorrect.
https://example.com/customers/NameIWant.php
returns: NameIWan
https://example.com/customers/NameIWant.php?someting
returns: NameIWan.php?someting
$url= basename($_SERVER['REQUEST_URI'], '.php' . $_SERVER['QUERY_STRING'])
This $url I will use it to query MySQL.
And I don't need query in URL or any code only the name of the current file.
You can use parse_url() and basename() to get the filename only:
<?php
$url = 'https://example.com/customers/NameIWant.php?someting';
// /customers/NameIWant.php
$path = parse_url($url, PHP_URL_PATH);
// NameIWant
$filename = basename($path, '.php');
(Replace $url = 'https://example.com/customers/NameIWant.php?someting'; with $url = $_SERVER['REQUEST_URI'];)
https://www.php.net/manual/en/function.parse-url.php
https://www.php.net/manual/en/function.basename.php
I need get file folder name from url
examples:
http://domain/folder/NEEDTHIS/filename.xml
http://domain/folder/folder2/NEEDTHIS/filename.xml
http://domain/folder/folder2/folderanother/NEEDTHIS/filename.xml
I need only "NEEDTHIS" folder name only
i using this code for get file name
$parts = parse_url("http://domain/folder/NEEDTHIS/filename.xml");
$title = basename($parts['path']);
echo $title;
// Output: filename.xml
How can i get this file name folder?
With this approach you can even avoid parse_url()...:
$url = "http://domain/folder/NEEDTHIS/filename.xml";
$items = explode('/', $url);
echo $items[sizeof($items) - 2];
// Output: NEEDTHIS
Note: this solution only assumes directories/filenames are separated by a character. To be even more general, you could use DIRECTORY_SEPARATOR:
$url = "http://domain/folder/NEEDTHIS/filename.xml";
$items = explode(DIRECTORY_SEPARATOR, $url);
echo $items[sizeof($items) - 2];
Here you go. Use dirname() to get simple one-liner that works both for URL and normal dir-paths. Works too, if no file is specified in path (or when path ends at dir).
$path = 'http://example.com/root/one/two/three/four.xml';
echo end(explode('/',dirname($path)));
Outputs:
three
You can replace $path with anything.
Try this:
$url = "http://domain/folder/folder2/folderanother/NEEDTHIS/filename.xml";
$array = explode('/',$url);
$count = count($array);
echo $array[$count-2];
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];
I have a little snippet that grab's the filename, including the extension.
$currURL = substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
given a url... http://www.somewebsite.com/pretty/url/here/this-is-a-page.php it returns this-is-a-page.php. I would like to be able to return simply, this-is-a-page.
I'm pretty obsessive about doing stuff like this in as little code as possible... how would you do this in a simple and elegant manner?
Try this:
$name = pathinfo($_SERVER['SCRIPT_NAME'], PATHINFO_FILENAME);
Test:
$arr = array('http://www.example.com/path/to/page.php',
'http://www.example.com/path/to/page.php?a=b&c=d#e',
'http://www.example.com/path/to/page.x.php',
'www.example.com/path/to/page.php',
'/path/to/page.php');
foreach ($arr as $str) {
$name = pathinfo($str, PATHINFO_FILENAME);
echo $name . '<br />';
}
Output:
page
page
page.x
page
page
$file_no_ext = preg_replace(
array('#^.*/#', '#\.[^./]+$#'), '', parse_url($url, PHP_URL_PATH));
e.g.
http://example.com/fds.php/path/file
=> file
http://example.com/fds.php/path/file.php
=> file
http://example.com/fds.php/path/file.php2.php?abc=a
=> file.php2
Another solution is
$file_no_ext = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_FILENAME);
This works for .php files
rtrim(substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1),".php");
echo substr(strstr($url,'.php',TRUE),strrpos($url,'/')+1)
or
preg_match('/[^\/]+(?=\.php)/',$url,$match);
echo $match[0];
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