Form code
<form action=<?=$_SERVER['PHP_SELF']?> method="POST" id="form1">
Enter length of password:<input type="text" name="length">
<input type="submit" value="Submit"/>
PHP code
<?php
$length=$_POST['length']
?>
Error:
Undefined array key "length" in D:\XWAMP\htdocs\pg\index2.php on line 30
I'm writing both html and php in single file that's why it's happening but how to handle it?
CodePudding user response:
I assume the web page loads and you get the error. In this case, you haven't check whether the form is submitted. Before the form is submitted you also haven't added a name for your submit button.
if(isset($_POST['submit'])){
$length = $_POST['length'];
}
This should solve your problem I suppose. A similar question was asked here: Check if form was submitted
CodePudding user response:
Various issues,
action=<?=$_SERVER['PHP_SELF']?>
is open to XSS don't use it- To check if its POST request, use
$_SERVER['REQUEST_METHOD'] === 'POST'
- Always validate user input and respond in kind to the user
<?php
$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// validate length
if (!isset($_POST['length'])) {
$errors['length'] = 'Length is a required field';
} else if (!is_numeric($_POST['length'])) {
$errors['length'] = 'Length should be a number';
} else if ($_POST['length'] < 1) {
$errors['length'] = 'Length should be a >= then 1';
} else if ($_POST['length'] > 1000) {
$errors['length'] = 'Length should be a <= then 1000';
}
// no errors, do processing on length
if (empty($errors)) {
$length = $_POST['length'];
// do something with $length
}
}
?>
<form action="" method="POST" id="form1">
Enter length of password:
<input type="text" value="<?= isset($_POST['length']) ? htmlentities($_POST['length']) : '' ?>" name="length" required>
<?= isset($errors['length']) ? '<div >'.$errors['length'].'</div>' : '' ?>
<input type="submit" value="Submit"/>
</form>