Home > database >  PHP Variable assignment does not work as expected
PHP Variable assignment does not work as expected

Time:12-16

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.

CodePudding user response:

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

CodePudding user response:

Why not write something like that ?

$browser = $_GET['browser'];
$version = $_GET['version'];
$page = $_GET['page'];

CodePudding user response:

The secure way of reading $_GET would be to use filter_input()

$browser = filter_input(INPUT_GET, 'browser');
$version = filter_input(INPUT_GET, 'version');
$page = filter_input(INPUT_GET, 'page');

https://www.php.net/manual/en/function.filter-input.php

But with regurads to original question, the issue is with (strcmp($key, "browser")) should be (strcmp($key, "browser") == 0) where 0 indicates a match. But if no condition is specified for if() then 0 will read FALSE

  • Related