views:

146

answers:

4

I'm trying to grab each URL parameter and display them from first to last, but I want to be able to display any of the parameters anywhere on the page. How can I do this? What do I have to add or modify on my script?

Here is an example of a URL value.

http://www.localhost.com/topics/index.php?cat=3&sub1=sub-1&sub2=sub-2&sub3=sub-3&sub4=sub-4

Here is my PHP script.

$url = $_SERVER['QUERY_STRING'];
$query = array();

if(!empty($url)){
  foreach(explode('&', $url) as $part){
    list($key, $value) = explode('=', $part, 2);
    $query[$key] = $value;
  }
}
+8  A: 

You don't need to do that manually, PHP already provides this functionality in the $_GET global variable:

<?php
    foreach($_GET as $key => $value)
        echo $key . " : " . $value;
?>
Daff
And Ye Gods, don't forget to filter those... whether they're displayed back to the user immediately or get stored in a database or broadcast into deep space, nefarious (or incompetent) users can cause all kinds of problems. Please make sure to escape them properly.
CaseySoftware
A: 

You're looking for the $_GET superglobal

 foreach ($_GET as $key => $value) {
    echo $key . ' -- ' . $value;
}

You can access any $_GET values by using this code $_GET['sub1'] which will return sub-1

Stoosh
+1  A: 

If it is a GET request, then all the params will be in $_GET. A form POST will be in $_POST. Both are contained in $_REQUEST.

Brent Baisley
A: 

There is a much simpler way to do this rather than using a loop. Use the built in function parse_str(). It will split the request uri into key => value pairs. Example:

$url = "cat=3&sub1=sub-1&sub2=sub-2&sub3=sub-3&sub4=sub-4";
$query = array();
parse_str( $url, $query );
print_r($query);
jrtashjian