-1

I'm getting the following error:

Notice: Undefined index: test

With reference to this line:

$token = htmlspecialchars($_GET["test"]);  

Do I need to define test somewhere even though I'm trying to read it from a URL?

-

-EDIT-

I had actually looked at the answer linked as a duplicate before posting this but couldn't see anything in it relating to using htmlspecialchars which I thought was causing the problem.

Robert
  • 5,278
  • 43
  • 65
  • 115
  • 1
    Try outputting `var_dump($_GET)` and see if "test" key exists. It'd be good if you do an `isset` check before you use it directly – Kamehameha Oct 12 '15 at 10:12
  • Possible duplicate of [PHP: "Notice: Undefined variable" and "Notice: Undefined index"](http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index) – Epodax Oct 12 '15 at 10:25

6 Answers6

2

Your variable doesn't exists. Use isset to check this

if(isset($_GET["test"]))
    $token = htmlspecialchars($_GET["test"]); 
else
    echo "variable test doesn't exist";
Harshit
  • 5,147
  • 9
  • 46
  • 93
  • All informative answers here but I used this one and it worked so will accept this as answer as soon as SO allows. Thanks. – Robert Oct 12 '15 at 10:22
2

You have to enable the error reporting on by using the below line before the script runs

error_reporting(E_ALL);

Then check the variable exists before you use by using the isset() function in php

isset($_GET["test"])
Manigandan Arjunan
  • 2,260
  • 1
  • 25
  • 42
TimLY
  • 21
  • 2
1

Check that $_GET["test"] exists before you apply htmlspecialchars to it. This sets the token value to null if $_GET["test"] is not set.

$token = isset($_GET["test"]) ? htmlspecialchars($_GET["test"]) : null;
Gravy
  • 12,264
  • 26
  • 124
  • 193
  • It checks to see if `$_GET["test"]` is set before trying to perform an operation on something which doesnt exist. – Gravy Oct 12 '15 at 10:18
1

You are not supplying the test variable in the GET request therefore it displays this error. Try using the code suggested by Gravy. Though this will make the token null if test is not received in URL. IF token is a mandatory requirement to be received them you can do something like

if(isset($_GET['test'])) {
    $token = htmlspecialchars($_GET["test"]);
}else{
    // do stuff when you dont get test. Return or output error etc.
}
Ashish Choudhary
  • 2,004
  • 1
  • 18
  • 26
1

As you mentioned , to read from url .. It doesn't guaranteed that you page is requested through get ,, it may be post .. To work on both use

$token = htmlspecialchars($_REQUEST["test"]);  
Rohit Kumar
  • 1,948
  • 1
  • 11
  • 16
1

$token = htmlspecialchars(@$_GET["test"]);

Use @ to ignore notice error