I have search high and low for an answer to my question and I cannot find it. Basically what I want to do is get the path after a php script. ex. "http://www.example.com/index.php/arg1/arg2/arg3/etc/" and get arg1, arg2, arg3, etc in an array. How can I do this in php and once I do this will "http://www.example.com/arg1/arg2/arg3/etc" still return the same results. If not then how can I achieve this?
Asked
Active
Viewed 2,560 times
3 Answers
5
Here is how to get the answer, and a few others you will have in the future. Make a script, e.g. "test.php", and just put this one line in it:
<?php phpinfo();
Then browse to it with http://www.example.com/test.php/one/two/three/etc
Look through the $_SERVER
values for the one that matches what you are after.
I see the answer you want in this case in $_SERVER["PATH_INFO"]: "/one/two/three/etc"
Then use explode
to turn it into an array:
print_r( explode('/',$_SERVER['PATH_INFO'] );
However sometimes $_SERVER["REQUEST_URI"]
is going to be the one you want, especially if using URL rewriting.
UPDATE:
Responding to comment, here is what I'd do:
$args = explode('/',$_SERVER['REQUEST_URI']);
if($args[0] == 'index.php')array_shift($args);

Darren Cook
- 27,837
- 13
- 117
- 217
-
Nice answer but before I accept it I need to know if it is possible to make http://www.example.org/arg1/arg2 act the same as http://www.example.org/index.php/arg1/arg2. – john01dav Nov 21 '13 at 06:01
-
@john01dav So the same script can be used for either way of being called? Yes, use REQUEST_URI, explode out, then filter out "index.php" if it is there. I'll update my answer. – Darren Cook Nov 21 '13 at 06:54
-
No, I mean actually making the script be loaded like that and not interpreted as a directory as it currently is. – john01dav Nov 21 '13 at 22:59
-
@john01dav That is a distinctly different question. Short answer is it is done with Apache config. E.g. see: http://stackoverflow.com/questions/5214502/how-to-redirect-all-requests-to-index-php-and-keep-the-other-get-params – Darren Cook Nov 21 '13 at 23:16
1
Try like this :
$url ="http://www.example.com/index.php/arg1/arg2/arg3/etc/";
$array = explode("/",parse_url($url, PHP_URL_PATH));
if (in_array('index.php', $array))
{
unset($array[array_search('index.php',$array)]);
}
print_r(array_values(array_filter($array)));

Mahmood Rehman
- 4,303
- 7
- 39
- 76
-
I went to write something like this, then realized it will mess up this URL: example.com/arg1/index.php/arg3/ I.e. when one of the arguments is the magic string "index.php". Of course, the OP cannot do what he wants to do if index.php could validly be the first argument! – Darren Cook Nov 21 '13 at 06:58
0
Can you try using parse_url
and parse_str
$url =$_SERVER['REQUEST_URI'];
$ParseUrl = parse_url($url);
print_r($ParseUrl);
$arr = parse_str($ParseUrl['query']);
print_r($arr);

Krish R
- 22,583
- 7
- 50
- 59