1

How can I create a form that accept number only?

<!DOCTYPE html>
<html>
<body>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
    <label>x:</label><br>
    <input type="text"  name="xx" ><br>
    <input type="submit" value="Submit">
</form>
<?php
if (isset($_POST['xx']) || !empty($_POST['xx']) || is_numeric($_POST['xx'])){
    $x = $_POST['xx'];
}else{
    echo "vous devez taper des chiffres!";
}
echo $x . "<br />";
?>
</body>
</html>

I am new in PHP please an easy answer. Thank you :-)

user3783243
  • 5,368
  • 5
  • 22
  • 41
John7911
  • 29
  • 3
  • What happens with this code? It should validate once the form is processed. `isset` and `!empty` are 99% of the time redundant. – user3783243 Mar 24 '20 at 18:21
  • `` is open to XSS injections. https://stackoverflow.com/questions/6080022/php-self-and-xss – user3783243 Mar 24 '20 at 18:21
  • What is the best solution for this small example? Thank you. – John7911 Mar 24 '20 at 18:46
  • 1
    i changed to this for the XSS Injection :
    ">
    – John7911 Mar 24 '20 at 18:50
  • Does this answer your question? [How to check if the value is number or string for a field with type 'character varying' in php?](https://stackoverflow.com/questions/50723369/how-to-check-if-the-value-is-number-or-string-for-a-field-with-type-character-v) – fork2execve Mar 25 '20 at 01:06

2 Answers2

1

If you only want to accept a number, you can also do so using the html element <input>. Like this:

<input type= "number" name= "xx">

As a precaution, check the server-side $ _POST["xx"] element. Whether the element contains the expected values.

Like this:

check whether the element has been filled in and does not contain only white characters. And remove any white space before and after the number using trim()

$xx = trim($_POST["xx"]);

if(!empty($xx) && is_numeric($xx)) {
   // if "if-condition" true
} else {
   // if "if-condition" false
}
1

I have this message if it is empty enter image description here

<!DOCTYPE html>
<html>
<body>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, "utf-8"); ?>">
    <label>x:</label><br>
    <input type="number"  name="xx" ><br>
    <input type="submit" value="Submit">
</form>

<?php
$value = trim($_POST["xx"]);

if(!empty($value) && is_numeric($value)) {
    $xxx = $_POST['xx'];
} else {
    echo "vous devez taper des chiffres!";
}
echo $xxx . "<br />";
?>
</body>
</html>

It is not an answer this, I don't know how to add code in the comment.

John7911
  • 29
  • 3