简体   繁体   中英

How to dynamically get variables from query in PHP

So i am trying to implement a PHP program in which you can put in basically any kind of key and value given in the url query. So for example if i would put "www.domain.se/dispatch.php?randomkey=randomvalue" it would echo "randomkey=randomvalue" but if i then right in the browser add to it "www.domain.se/dispatch.php?randomkey=randomvalue&secondkey=secondvale" it would echo "randomkey=randomvalue secondkey=secondvalue"

Right now i have only managed to get the first given key with this code and dont know how to move on. Any ideas? This is my code in dispatch.php:

      <?php
      $query = $_SERVER['QUERY_STRING'];
      echo key($_GET);
      ?>

You can use print_r function to print an array in human readable format:

<?php print_r($_GET); ?>

or if you want to also see types use var_dump function:

<?php var_dump($_GET); ?>

If your practice is to use for loop this is answer:

for( $_GET as $key => $value )
    echo "$key : $value <br>";

Use above codes only for debug or during test period not in a production site to prevent security issues. Also consider using htmlspecialchars to prevent cross site scripting attacks.

So this piece of code nailed it:

    <?php
$query = ($_GET);
foreach ($query as $key => $value) {
    print_r($key. ": ". $value);
    echo '<br/>';
}
?>

But for anyone reading. Be aware as this is for school and as i have been warned this is not a secure way to deal with this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM