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
Related
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"
I have the following URLs:
http://website.com/folder1/file.php
http://website.com/folder2/file.html
I want to know if there is any way in PHP that will let me hide the files and their extensions so the URLs will look like this:
http://website.com/folder1/
http://website.com/folder2/
I know this is possible using htaccess and mod_rewrite but I want to do it using PHP only.
ok I found the answer :
<? echo dirname("http://website.com/folder1/file.php"); ?>
so the url will look like this :
http://website.com/folder1/
dirname removes the last part of the URL.
To remove a specific string at the end of the URL if it exists, use rtrim:
$url = rtrim($url, 'file.php');
// http://website.com/folder/
$url = rtrim($url, '/');
// http://website.com/folder
Or a way via file extension detection:
function removeFilenameFromURL($url)
{
$urlPath = pathinfo($url);
// Remove if the URL has an file extension
if (isset($urlPath['extension'])) {
$lastPos = strripos($url, "/");
$url = substr($url, 0, $lastPos + 1);
}
return $url;
}
echo dirname("https://localhost/subdir/index.php") . "<br>";
echo removeFilenameFromURL("https://localhost/subdir/index.php") . "<br>";
echo phpversion();
OUTPUT:
https://localhost/subdir
https://localhost/subdir/
7.4.23
This always ensures a trailing slash.
ATTENTION:
With dirname() function on PHP 7.4 the trailing slash is gone ... (changing behavior on different PHP versions??)
I am trying to do a URL parser for my project, something very simple that gets an URL like you would enter it in a browser and convert it into a valid URL, once that is done parse such URL and grab all the images with full paths.
I was able to "fix" the user entered URL and pre-pend the http when needed, remove the last / on domain only (`http://www.domain.com/ become http://www.domain.com but http://www.domain.com/test/ stays unchanged).
The problem that I am having is dirname is parsing the path of certain folders.
my code looks something like this:
<?php
$url = 'www.domain.com/~folder/'; //This is a variable that changes often
$url = $this->fix_url($url); //$url is now http://www.domain.com/~folder/
$url_image = 'image.png';
$parse = parse_url($url);
$dir = (isset($parse['path'])?dirname($parse['path']):'');
$ret = 'http://'.$parse['host'].$dir.'/'.$url_image;
var_dump($parse, $dir, $ret);
?>
The way I was able to go around the problem is with this code that I use to find $dir
<?php
$path = (isset($parse['path'])?$parse['path']:'/');
$tmp = explode('/', $path);
if(is_array($tmp) && count($tmp) > 0){
array_pop($tmp);
}
$dir = implode('/', $tmp);
?>
But there must be a better way
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];
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