2

I'm asking for your help because I would like to automate something in my form processing in PHP.

My goal is to know the HTML type of a $_POST variable. For example, if it is a <input type="number" name="tata">, in my PHP processing, I would like to transform the content as (int) $_POST['tata'] and make some verification.

The final goal is to be able to use one verification for all my fields and all my forms on my website to convert the variables as the good format I'm waiting before sending data to my database.

Is there any way to do this in PHP ? I know that I can get the type with jQuery but I would like to avoid this method.

Thank you for your answers

4
  • gettype might be of interest to get you started Commented Nov 7, 2019 at 21:09
  • if type="number" only integer will allowed, you can also use is_numeric($_POST['tata']) to check if the value is a number or not Commented Nov 7, 2019 at 21:10
  • 3
    All values sent to the server will be parsed as strings, no matter the value. PHP won't know if the value "1337" came from a type="number" or type="text"-field. What you can do is to add hidden fields with the input types for each normal input field Commented Nov 7, 2019 at 21:10
  • gettype will not help me is_numeric will not help me too because I would like to automate all my verifications with a foreach on all my POST fields @MagnusEriksson, you're right, It can be a way to do my stuff thanks ;) Commented Nov 7, 2019 at 21:14

1 Answer 1

3

All values sent to the server will be parsed as strings, no matter the value. PHP won't know if the value "1337" came from an input with type="number" or type="text"-field. Those types are simply for the UI on the client.

What you can do is to add hidden fields with the input types for each normal input field.

Example:

<input type="number" name="num[value]" value="1337" />
<input type="hidden" name="num[type]" value="number" />

If you do that for each input, then you can validate each value on the server:

// Access a value directly
$type  = $_POST['num']['type'];
$value = $_POST['num']['value'];

// Or iterate through the items and do something
foreach ($_POST as $key => $param) {
    $type  = $param['type'];
    $value = $param['value'];

    // Do your thing...
}

Note

This is not a secure way of automating validation on the server. Since the data comes from the client, none of it can really be trusted. If someone wants to send in invalid data, they could simply change the type in the form before posting.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.