-2

I'm trying to redirect from JS and include a variable that will be accessible via $_GET for PHP, like so:

let destination = "viewmode.php?id=" + id
window.location.href = destination;

Once I get to the PHP in the other page, this

print $_GET['id'];

Only raises error "Undefined index: id"

From the url I can tell that the variable exists... right?

...ne/viewmode.php?id=7

So,

1- Is it okay to pass a variable simply by modifying the url in JS?

2- Does PHP's $_GET method simply rely on the url to access the requested values?

If the answer to #2 is yes, then why can't PHP find the index "id"?

PS: I know I should be using if(isset($_GET['id']) once I'm done debugging

Félix Paradis
  • 5,165
  • 6
  • 40
  • 49
  • 1
    If `if(isset($_GET['id'])) {` yields false it wouldn't hit the code which causes the warning. Your looking in the wrong place or this is not the code. – Lawrence Cherone Dec 12 '17 at 03:46
  • That question only says I should check that the variable isset() and that "For $_POST and $_GET you just have to check if the index exists or not before you use them", that is pretty much my question, since I can see it in the URL, can't I assume it is set? – Félix Paradis Dec 12 '17 at 03:58
  • How about `var_dump($_GET);` before your `print $_GET['id'];` line? Where exactly do you see that error; on the page itself or somewhere else like the browser console? – Phil Dec 12 '17 at 03:58
  • var_dump($_GET); throws the same error, Phil. (thx) – Félix Paradis Dec 12 '17 at 04:00
  • All variable should be declared and checked before use, in any language. php is just loosely typed, so it throws warning instead of fatal errors. – Lawrence Cherone Dec 12 '17 at 04:00
  • 1
    @FelDev that is quite literally impossible. `var_dump($_GET)` should not throw any errors. At a minimum, it would display `array(0) { }` – Phil Dec 12 '17 at 04:00
  • @Phil you are very right! it does display array(0) { } – Félix Paradis Dec 12 '17 at 04:03
  • So, where exactly do you see that error; on the page itself or somewhere else like the browser console? Does you server have any URL rewriting enabled (like in a `.htaccess` file)? Try `var_dump($_SERVER);`, that will contain a lot of useful information. – Phil Dec 12 '17 at 04:05
  • The error is in the console, looking up `var_dump($_SERVER);` right now... – Félix Paradis Dec 12 '17 at 04:06
  • 1
    Right, so if it's in the console, it's probably coming from an AJAX request. PHP doesn't usually write to the browser console. Somewhere, you have another request to `viewmode.php` that does not include the query parameter. You should be able to clearly see it in your browser's *Network* console – Phil Dec 12 '17 at 04:12
  • @Phil, thanks a lot, I'll look for that. – Félix Paradis Dec 12 '17 at 04:18

1 Answers1

-1

Try using $_REQUEST['id'], I think this is what you are after.