开发者

How do I get the filename without the params?

开发者 https://www.devze.com 2023-03-03 01:21 出处:网络
I need to find the file name of the file I\'ve included without the GET parameters. e.g.: if the current URL is http://www.mysite.com/folder/file.php?a=b&c=d ,

I need to find the file name of the file I've included without the GET parameters.

e.g.: if the current URL is http://www.mysite.com/folder/file.php?a=b&c=d , i want file.php returned

what I have found:

basename($_SERVER['REQUEST_URI'])

which returns:

file.php?a=b&c=d

in my case: I'm using the filename in a form in the section for my cart, so at the moment each time you click the 'reduce number of product' button it adds the GET params of the form (productId and action) to the end of the URL: file.php?a=b&c=d?a=b&c=d?a=b&c=d?a=b&c=d...

I know I could simply explode or something similar on '?'

$file = explode("?", basename($_SERVER['REQUEST_URI']))

and use the开发者_JAVA技巧 first part of the array, but I seem to recall something easier, however cannot locate the code again..

I'm new to PHP so explanation on your code would be appreciated.

Thanks, V


You can make use of parse_url. In your case you could use:

$url = parse_url($url, PHP_URL_PATH);

To get only the file name you can do something like this:

$url = explode('/', parse_url($url, PHP_URL_PATH));
$url = end($url);


Maybe you are looking for $_SERVER['PHP_SELF'].

Please notice that it has a '/' char in the beginning.


Have you tried a simple basename(__FILE__);? This will get you the filename of where the code is located, as it is on disk.

For getting the requested file, you can use basename($_SERVER['SCRIPT_NAME']);. This will always get the file that was requested, rather than the file that the code is contained within.


basename(parse_url($url,PHP_URL_PATH));

parse_url($url,PHP_URL_PATH) erase params. basename() get filename of path.


basename($_SERVER['SCRIPT_NAME']);

This will do it.

In addition it is always good to know some given variables. The following snippet in a php file is really useful.

<pre><?php
print_r($_SERVER);
?></pre>


The best solution for me:

$file = basename(parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH));


Take a look at some of the other values in $_SERVER.

Maybe $_SERVER["PHP_SELF"] or $_SERVER["SCRIPT_NAME"] will return what you want.


This is the closest I've found. Here's how I did it:

$url = parse_url($_SERVER['PHP_SELF'], PHP_URL_PATH);
$url = explode('/', parse_url($url, PHP_URL_PATH));
$url = end($url);
error_log($url);


The only way that you get the name of the script without the parameters is making a POST request

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号