phpissetsuperglobals

Using isset and filter_input the correct way in PHP


I am developing a basic API for some simple functionality. I am capturing inputs like below:

if ($action == 'delete' && isset($_POST['targetId']) && isset($_POST['userId'])) {
//The isset causes "Do not access Superglobal _POST array directly" warning in Netbeans
        $userId = filter_input(INPUT_POST, 'userId');
        $beamId = filter_input(INPUT_POST, 'targetId');
}

Should I use filter_input even for checking whether the value is set? Like:

if ($action == 'delete' && filter_input(INPUT_POST, 'targetId') && filter_input(INPUT_POST, 'userId')) {

}

I am not looking at options here rather I would be happy with the most correct solution which is secure and hack resistant.

EDIT: Yes, the above information will be used as inputs for SQL


Solution

  • filter_input is used to sanitize or check the data type of the input. It is used to make sure that the data you are expecting is in the required format and you can sanitize it using required filters. isset in your case will check if the required variable is set or not (or is not NULL). So both have different usecases. I don't see using isset directly on a POST item as bad but I would recommend using filter_input so that the data can be validated as well.