Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP Variable assignment does not work as expected

I am trying to assign parameters listed in the URL save into my variables. You can see the procedure here:

<?php

$browser;
$version;
$page;

foreach($_GET as $key => $value) {
  if (strcmp($key, "browser")) {
    $browser = $value;
  }
  elseif (strcmp($key, "version")) {
    $version = $value;
  }
  elseif (strcmp($key, "page")) {
    $page = $value;
  }
}

echo $browser;
echo $version;
echo $page;
?>

But unfortunately, it only prints out the browser and the version. The page does not appear. Yes, the page parameter is definitely written correctly in the URL. If I change code like this, the variables get printed out correctly:

 <?php
    
    foreach($_GET as $key => $value) {
      if (strcmp($key, "browser")) {
        echo $value;
      }
      elseif (strcmp($key, "version")) {
        echo $value;
      }
      elseif (strcmp($key, "page")) {
        echo $value;
      }
    }
    ?>  

Link shematik: ./bglink/addstats.php?browser=Chrome&version=96&page=index
Thanks in advance.
Filip.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

strcmp doesn’t do what you think it does.

It can return -1, 0 or 1 depending on the comparison of the two string, not true or false. Your loop isn’t finding the strings that are equal, it actually will print the first case where $key does not equal the string you’re asking about, since both -1 and 1 will evaluate to true.

Running your original code with some extra debug output shows that you’re actually overwriting the variables with other elements from the loop:

Browser: my page
Version: my browser
Page: 

See https://3v4l.org/QFSAl

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading